<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80">
        <el-form-item class="!mr-0" label="完成时间" prop="timeScopes">
          <el-date-picker
            v-model="timeScopes"
            @change="validateYearRange"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          />
        </el-form-item>
        <el-form-item label="盘库任务" prop="name">
          <el-input
            v-noSpace
            v-model="queryParams.name"
            clearable
            class="!w-[192px]"
            @keyup.enter="handleSeach"
            placeholder="请输入盘库任务"
          />
        </el-form-item>
        <el-form-item label="盘库结果" prop="result">
          <el-select
            v-model="queryParams.result"
            placeholder="请选择盘库结果"
            clearable
            class="!w-[192px]"
            @change="handleSeach"
          >
            <el-option
              v-for="item in resultOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSeach">查询</el-button>
          <el-button icon="refresh" @click="handleReset">重置</el-button>
          <el-button
            @click="downloadTable"
            type="success"
            class="!rounded-button whitespace-nowrap"
            v-hasPerm="'sys:inventoryReport:exp'"
          >
            <el-icon class="mr-1"><Download /></el-icon>
            导出报表
          </el-button>
          <el-button
            @click="HistoryClick"
            type="info"
            class="!rounded-button whitespace-nowrap"
            v-hasPerm="'sys:inventoryReport:down'"
          >
            <el-icon class="mr-1"><Document /></el-icon>
            历史报表下载
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        show-overflow-tooltip
        :tooltip-formatter="tableRowFormatter"
        :data="tableData"
      >
        <el-table-column prop="name" label="盘库任务名称" min-width="200" sortable />
        <el-table-column prop="finishTime" label="盘库完成时间" min-width="180" sortable />
        <el-table-column prop="productName" label="盘库产品" min-width="150" sortable />
        <el-table-column prop="stockNum" label="库存数量" min-width="120" sortable />
        <el-table-column prop="checkNum" label="盘点数量" min-width="120" sortable />
        <el-table-column prop="unit" label="单位" min-width="100" sortable>
          <template #default="scope">
            {{ unitFormat(scope.row.unit) }}
          </template>
        </el-table-column>
        <el-table-column prop="result" label="盘库结果" min-width="120" sortable>
          <template #default="scope">
            <el-tag :type="getResultTagType(scope.row.result)" class="whitespace-nowrap">
              {{ scope.row.result }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleSeach"
      />
    </el-card>
    <!-- 历史报表下载弹窗 -->
    <el-dialog v-model="historyDialogVisible" title="历史报表下载" width="600px">
      <el-table :data="historyReports" style="width: 100%">
        <el-table-column prop="fileName" label="文件名称" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button @click="historyDownLoad(row.filePath, row.fileName)" type="primary" link>
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-model:total="peportTotal"
        v-model:page="reportParams.pageNum"
        v-model:limit="reportParams.pageSize"
        @pagination="reportHistoryList"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { tableRowFormatter } from "@/utils/index";
import { FormItemRule } from "element-plus/es";
import statementApi, { locationPageQuery } from "@/api/statement/statement";
import configApi, { ConfigType } from "@/api/config/config";
import { downLoad, historyDownLoad } from "@/utils/downLoad";
import { useDateRanges } from "@/utils/useDateRanges";
const historyDialogVisible = ref(false);
const reportType = 8;
const reportName = "盘点报表";
const historyReports = ref([]);
const peportTotal = ref(0);
const reportParams: locationPageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  reportType: reportType,
});
const reportHistoryList = () => {
  statementApi
    .getReportHistory(reportParams)
    .then((data) => {
      console.log(data);
      historyReports.value = [...(data.list as never)];
      historyReports.value.forEach((item: any) => {
        item.fileName = reportName + "_" + useDateRanges().getDate() + ".xlsx";
      });
      peportTotal.value = data.total;
    })
    .finally(() => {});
};
const HistoryClick = async () => {
  historyDialogVisible.value = true;
  reportHistoryList();
};
//下载表格
const downloadTable = () => {
  downLoad(queryParams, reportType, reportName);
};
// 加载loading
const loading = ref(false);
// 分页总数
const total = ref(0);
// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);
const unitFormat = (unit: any) => {
  if (!unit) return;
  let unitLabel = unitOptions.value.find((item) => item.value === unit.toLowerCase())?.label;
  return unitLabel;
};
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};
// 搜索ref
const queryFormRef = ref(ElForm);
const timeScopes = ref([]);
const groupChange = () => {
  timeScopes.value = [];
};
// 限制选择范围不超过365天
const validateYearRange = (val: any) => {
  if (!val || val.length !== 2) {
    return;
  }

  const [start, end] = val;
  const startDate = new Date(start);
  const endDate = new Date(end);

  // 计算两个日期之间的年份差
  const yearDiff = endDate.getFullYear() - startDate.getFullYear();
  const monthDiff = endDate.getMonth() - startDate.getMonth();
  const dayDiff = endDate.getDate() - startDate.getDate();

  // 如果年份差大于1年，或者正好1年但结束月份/日期大于开始月份/日期
  if (yearDiff > 1 || (yearDiff === 1 && (monthDiff > 0 || (monthDiff === 0 && dayDiff > 0)))) {
    ElMessage.error(`选择的时间范围不能超过一年`);

    timeScopes.value = [];
  }
};

const getResultTagType = (result: string) => {
  switch (result) {
    case "盈":
      return "success";
    case "亏":
      return "danger";
    case "平":
      return "info";
    default:
      return "info";
  }
};

const queryParams: locationPageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
});

const resultOptions = [
  { value: "盈", label: "盈" },
  { value: "亏", label: "亏" },
  { value: "平", label: "平" },
];

// 列表参数
const tableData = ref([]);

// 查询方法
const handleSeach = () => {
  loading.value = true;
  queryParams.startDate = timeScopes.value[0];
  queryParams.endDate = timeScopes.value[1];
  statementApi
    .getCheckReport(queryParams)
    .then((data) => {
      tableData.value = [...(data.list as never)];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
// 重置方法
const handleReset = () => {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  timeScopes.value = [];
  handleSeach();
};

onMounted(() => {
  handleSeach();
  getUnitList();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
